package com.cn.jinl.service;


import com.cn.jinl.api.IFileInfoService;
import com.cn.jinl.api.ISysInfoService;
import com.cn.jinl.dao.SysInfoMapper;
import com.cn.jinl.domain.SysInfo;
import com.cn.jinl.domain.SysInfoExample;
import com.cn.jinl.utils.CollectionsUtil;
import com.cn.jinl.utils.CommonUtil;
import com.cn.jinl.utils.Constants;
import com.cn.jinl.utils.QueryForm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysInfoServiceImpl implements ISysInfoService {

    @Autowired
    private SysInfoMapper sysInfoMapper;

    @Autowired
    private IFileInfoService fileInfoService;

    @Override
    public SysInfo getSysInfoList(QueryForm queryForm) throws Exception {
        SysInfoExample example = new SysInfoExample();
        SysInfo sysInfo = new SysInfo();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS);
        example.setOrderByClause("update_time DESC");
        List<SysInfo> list = sysInfoMapper.selectByExample(example);
        if(CollectionsUtil.isNotEmpty(list)){
             sysInfo = list.get(0);
        }
        return sysInfo;
    }

    @Override
    public SysInfo getApiSysInfoList(QueryForm queryForm) throws Exception {
        SysInfo sysInfo = this.getSysInfoList(queryForm);
        String fileUrl = fileInfoService.getAppFileImagePath();
        sysInfo.setFileUrl(fileUrl);
        return sysInfo;
    }

    @Override
    public String addSysInfo(SysInfo sysInfo) throws Exception {
        sysInfo.setId(CommonUtil.generateRandomNum("sysInfo-"));
        int count = sysInfoMapper.insertSelective(sysInfo);
        return CommonUtil.outStr(count);
    }

    @Override
    public String addOrUpdateSysInfo(SysInfo sysInfo) throws Exception {
        String id = sysInfo.getId();
        if(StringUtils.isEmpty(id)){
            SysInfo exist = this.getSysInfoList(new QueryForm());
            if(StringUtils.isEmpty(exist.getId())){
                return this.addSysInfo(sysInfo);
            }
            sysInfo.setId(exist.getId());
        }
        return this.updateSysInfo(sysInfo);
    }

    @Override
    public String updateSysInfo(SysInfo sysInfo) throws Exception {
        String id  = sysInfo.getId();
        if(StringUtils.isBlank(id)){
            return "updateDtcSysInfo id 为空";
        }
        SysInfoExample example = new SysInfoExample();
        example.createCriteria().andIdEqualTo(id);
        int count = sysInfoMapper.updateByExampleSelective(sysInfo,example);
        return CommonUtil.outStr(count);
    }

    @Override
    public String deleteSysInfo(String ids) throws Exception {
        return null;
    }
}
